Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
今天原本要寫的題目沒寫出來,所以拿以前寫過的DFS/BFS 題目趕緊頂一下><
Example 1
Input: root = [1,2,2,3,4,4,3]
Output: true
1
/ \
2 2
/ \ / \
3 4 4 3
Example 2
Input: root = [1,2,2,null,3,null,3]
Output: false
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true; //空樹自動對稱
return isMirror(root -> left, root -> right);
}
private:
bool isMirror(TreeNode* t1, TreeNode* t2){
if(!t1 && !t2) return true;
if(!t1 || !t2) return false;
// 左子樹的左 vs 右子樹的右 AND 左子樹的右 vs 右子樹的左
return (t1 -> val == t2 -> val)&&
isMirror(t1 -> left, t2 -> right)&&
isMirror(t1 -> right, t2 -> left);
} //三個條件都要成立才會是對稱,所以用&&
};
#include <queue>
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (!root) return true; //空樹自動對稱
queue<TreeNode*> q;
q.push(root->left);
q.push(root->right);
while (!q.empty()) { //queue還沒空時
TreeNode* t1 = q.front(); q.pop();
TreeNode* t2 = q.front(); q.pop();
if (!t1 && !t2) continue; // 都空,對稱
if (!t1 || !t2) return false; // 一空一不空,不對稱
if (t1->val != t2->val) return false;
// 注意進入 queue 對稱順序
q.push(t1->left);
q.push(t2->right);
q.push(t1->right);
q.push(t2->left);
}
return true;
}
};
root | isSymmetric? |
---|---|
[1,2,2,3,4,4,3] | true |
[1,2,2,null,3,null,3] | false |
[1] | true |
[] | true |
isMirror(TreeNode* t1, TreeNode* t2)
:
isMirror(t2->right, t1->left)
會邏輯不對if (!t1 && !t2)
→ 兩個空指標 → 對稱if (!t1 || !t2)
→ 一個空 → 不對稱t1->left
vs t2->right
,t1->right
vs t2->left
if (!root) return true
→ 空樹自動對稱ps. 部分內容經 AI 協助整理